package com.buaa.aimall.userModule.Controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.buaa.aimall.computeModule.Service.ComputeService;
import com.buaa.aimall.goodsModule.Enum.GoodsTypeEnum;
import com.buaa.aimall.modelModule.Service.ModelService;
import com.buaa.aimall.userModule.DTO.*;
import com.buaa.aimall.userModule.Service.UserService;
import com.buaa.aimall.userModule.VO.ShoppingCartVO;
import net.minidev.json.JSONObject;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import com.buaa.aimall.Utils.BaseResponse;
import com.buaa.aimall.Utils.Enum.StatusCode;
import com.buaa.aimall.userModule.Entity.ShoppingCartEntity;
import com.buaa.aimall.userModule.Service.ShoppingCartService;

import jakarta.validation.Valid;

import com.buaa.aimall.userModule.Converter.ShoppingCartConvert;
import com.buaa.aimall.Utils.Exception.BusinessException;

import java.util.List;

@RestController
@RequestMapping("/user/shopping-cart")
@CrossOrigin
public class ShoppingCartController {
    @Autowired
    private ShoppingCartService shoppingCartService;
    @Autowired
    private UserService userService;
    @Autowired
    private ModelService modelService;
    @Autowired
    private ComputeService computeService;

    @PostMapping("/add-item")
    public BaseResponse<Boolean> addToShoppingCart(@RequestBody CreateShoppingCartItemDTO request) {
        ShoppingCartEntity shoppingCartEntity = ShoppingCartConvert.INSTANCE.createCartDTOToEntity(request);
        Boolean result;
        try {
            result = shoppingCartService.addToCart(shoppingCartEntity);
        } catch (BusinessException ex) {
            return new BaseResponse<>(StatusCode.DAO_ERROR, ex.getMessage(), null);
        }
        return new BaseResponse<>("创建购物车商品", result, result);
    }

    @PostMapping("/delete-item")
    public BaseResponse<Boolean> deleteFromShoppingCart(@Valid @RequestBody IdDTO request) {
        Boolean result;
        try {
            result = shoppingCartService.removeById(request.getId());
        } catch (BusinessException ex) {
            return new BaseResponse<>(StatusCode.DAO_ERROR, ex.getMessage(), null);
        }
        return new BaseResponse<>("删除购物车商品", result, result);
    }

    @PostMapping("/batch-delete-items")
    public BaseResponse<Boolean> batchDeleteFromShoppingCart(@Valid @RequestBody List<String> idList) {
        Boolean result = true;
        try {
            if (idList == null || idList.isEmpty()) {
                return new BaseResponse<>(StatusCode.PARAM_ERROR, "商品ID列表不能为空", false);
            }

            for (String id : idList) {
                Boolean singleResult = shoppingCartService.removeById(id);
                if (!singleResult) {
                    result = false;
                }
            }
        } catch (BusinessException ex) {
            return new BaseResponse<>(StatusCode.DAO_ERROR, ex.getMessage(), null);
        }
        return new BaseResponse<>("批量删除购物车商品", result, result);
    }

    @PostMapping("/update-item")
    public BaseResponse<Boolean> updateShoppingCartItem(@Valid @RequestBody UpdateShoppingCartItemDTO request) {
        try {
            Boolean result = shoppingCartService.updateCartItem(request);
            return new BaseResponse<>("更新购物车商品", result, result);
        } catch (BusinessException ex) {
            return new BaseResponse<>(StatusCode.DAO_ERROR, ex.getMessage(), null);
        }
    }

    @PostMapping("/get-shopping-cart-list")
    public BaseResponse<Page<ShoppingCartVO>> getShoppingCartList(@RequestBody ShoppingCartListDTO request) {
        var page = new Page<ShoppingCartEntity>(request.getCurrentPage(), request.getPageSize());
        var user = userService.getCurrentUser();
        var queryWrapper = new LambdaQueryWrapper<ShoppingCartEntity>();
        queryWrapper.eq(ShoppingCartEntity::getCreator, user.getId());
        if (request.getGoodsType() == GoodsTypeEnum.MODEL) {
            queryWrapper.ne(ShoppingCartEntity::getModelID, "");
        } else {
            queryWrapper.ne(ShoppingCartEntity::getComputeID, "");
        }
        var resultPage = shoppingCartService.page(page, queryWrapper);

        List<ShoppingCartVO> voList;
        if (request.getGoodsType() == GoodsTypeEnum.MODEL) {
            voList = resultPage.getRecords().stream().map(entity -> {
                ShoppingCartVO vo = new ShoppingCartVO();
                BeanUtils.copyProperties(entity, vo);
                vo.setModel(modelService.getById(entity.getModelID()));
                return vo;
            }).toList();
        } else {
            voList = resultPage.getRecords().stream().map(entity -> {
                ShoppingCartVO vo = new ShoppingCartVO();
                BeanUtils.copyProperties(entity, vo);
                vo.setCompute(computeService.getById(entity.getComputeID()));
                return vo;
            }).toList();
        }

        Page<ShoppingCartVO> responsePage = new Page<>();
        responsePage.setCurrent(resultPage.getCurrent());
        responsePage.setSize(resultPage.getSize());
        responsePage.setTotal(resultPage.getTotal());
        responsePage.setPages(resultPage.getPages());
        responsePage.setRecords(voList);

        return new BaseResponse<>(StatusCode.SUCCESS, "获取模型购物车列表成功", responsePage);
    }

    @GetMapping("/get-shopping-cart-count")
    public BaseResponse<JSONObject> getShoppingCartCount() {
        var user = userService.getCurrentUser();
        var queryWrapper = new LambdaQueryWrapper<ShoppingCartEntity>();
        queryWrapper.eq(ShoppingCartEntity::getCreator, user.getId());
        var count = shoppingCartService.count(queryWrapper);
        JSONObject data = new JSONObject();
        data.put("count", count);
        return new BaseResponse<>(StatusCode.SUCCESS, "获取购物车数量成功", data);
    }
}
